import requests
import time
import os
import sys
sys.path.append('../backend')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'HuaXianGuan.settings')

import django
django.setup()

from apps.flowers.models import Flower
from common.utils.oss_utils import FileOss

def crawl_tulip_images():
    """爬取郁金香图片"""
    
    # 郁金香图片URL - 更换为正确的郁金香图片
    tulip_urls = {
        "红郁金香花束": [
            "https://images.unsplash.com/photo-1518709268805-4e9042af2176?w=800&h=600&fit=crop",
            "https://images.unsplash.com/photo-1582794543139-8ac9cb0f7b11?w=800&h=600&fit=crop",
            "https://images.unsplash.com/photo-1490750967868-88aa4486c946?w=800&h=600&fit=crop",
            "https://images.unsplash.com/photo-1520637836862-4d197d17c90a?w=800&h=600&fit=crop"
        ],
        "粉郁金香花束": [
            "https://images.unsplash.com/photo-1490750967868-88aa4486c946?w=800&h=600&fit=crop",
            "https://images.unsplash.com/photo-1518709268805-4e9042af2176?w=800&h=600&fit=crop",
            "https://images.unsplash.com/photo-1582794543139-8ac9cb0f7b11?w=800&h=600&fit=crop",
            "https://images.unsplash.com/photo-1615887023516-7e36764c0df8?w=800&h=600&fit=crop"
        ]
    }
    
    oss_client = FileOss()
    
    for flower_name, urls in tulip_urls.items():
        print(f"\n开始处理: {flower_name}")
        
        # 查找对应的鲜花
        flower = Flower.objects.filter(name=flower_name).first()
        if not flower:
            print(f"未找到鲜花: {flower_name}")
            continue
        
        success = False
        
        for i, url in enumerate(urls):
            try:
                print(f"尝试下载图片 {i+1}: {url}")
                
                headers = {
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
                }
                
                response = requests.get(url, headers=headers, timeout=15)
                response.raise_for_status()
                
                # 生成OSS路径
                filename = f"{flower_name}.jpg"
                oss_path = f"flowers/{filename}"
                
                # 上传到OSS
                oss_url = oss_client.get_oss_image_url(oss_path, response.content)
                
                if oss_url:
                    # 更新鲜花的image字段
                    flower.image = oss_url
                    flower.save()
                    
                    print(f"✓ 成功上传: {flower_name} -> {oss_url}")
                    success = True
                    break
                else:
                    print(f"✗ OSS上传失败")
                    
            except Exception as e:
                print(f"✗ 下载失败: {e}")
                continue
        
        if not success:
            print(f"✗ 所有URL都失败了: {flower_name}")
        
        # 添加延迟
        time.sleep(2)

if __name__ == "__main__":
    crawl_tulip_images()
    print("\n郁金香图片爬取完成！")